package com.hongxun.design.jungong.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.activitys.RegeditActivity;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.fragments.BaseFragment;
import com.hongxun.design.jungong.activity.ProRecAndPicActivity;
import com.hongxun.design.jungong.model.SspPhoto;
import com.hongxun.design.jungong.model.SspRecord;
import com.hongxun.design.mytools.CheckUtil;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.ui.myiossheet.ActionSheet;
import com.hongxun.design.utils.PopwindowUtil;
import com.hongxun.design.utils.TimeUtil;
import com.hongxun.design.utils.camerautil.CameraUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.FileUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * Created by cqcqwucp 照片水印处理
 */

public class FragmentPhotoWaterMark extends BaseFragment implements View.OnClickListener {
    private View view;
    private TextView tv1, tv2, tv4, tv4img, tv6mark;
    private EditText et1;
    private ImageView iv1;
    private SspPhoto sspPhoto;
    private SspRecord record10;
    private int index = 0;
    private List<SspPhoto> photoListY, photoListN;
    private ArrayList<String> listType = new ArrayList<>();
    private boolean issave = false;
    private Bitmap bitmap0, bitmap1;
    private long fundtime = 0;
    private String path;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    tv4.setText(listType.get(msg.arg1));
                    break;
                //舍弃或保存当前照片数据后续操作
                case 2://舍弃
                    openSheet(getActivity(), "选择方式", "相册", "拍照");
                    break;
                case 3://保存
                    updatelocalData(3);
                    break;
                case 4://保存成功后续操作
                    hideWaitIngDialog();
                    ToastShow.showShort(getActivity(), String.valueOf(msg.obj));
                    if (msg.arg1 == 3) handler.sendEmptyMessage(2);
                    break;
            }
        }
    };

    public FragmentPhotoWaterMark() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.jg_fragmnet_photo_watermark, container, false);
        findViewById();
        return view;
    }

    @SuppressLint("NewApi")
    private void findViewById() {
        tv1 = (TextView) view.findViewById(R.id.fp_mark_tv1);
        tv1.setOnClickListener(this);
        tv2 = (TextView) view.findViewById(R.id.fp_mark_tv2);
        view.findViewById(R.id.fp_mark_tv3).setOnClickListener(this);
        view.findViewById(R.id.fp_mark_layout1).setOnClickListener(this);
        tv4 = (TextView) view.findViewById(R.id.fp_mark_tv4);
        tv4img = (TextView) view.findViewById(R.id.fp_mark_tv4_icon);
        view.findViewById(R.id.fp_mark_tv5).setOnClickListener(this);
        iv1 = (ImageView) view.findViewById(R.id.fp_mark_iv1);
        et1 = (EditText) view.findViewById(R.id.fp_mark_et1);
        tv6mark = (TextView) view.findViewById(R.id.fp_mark_tv6);
        tv6mark.setOnClickListener(this);

        SetTypeface.set(tv1, IconSourse.BACK);
        SetTypeface.set(tv4img, IconSourse.DROPDOWN);

        record10 = (SspRecord) getArguments().getSerializable(MString.key);
        sspPhoto = (SspPhoto) getArguments().getSerializable(MString.boyCode);
        index = Integer.valueOf(getArguments().getString(MString.before_number));

        tv2.setText(record10.getPileseat() + "\t" + record10.getKwords());
        tv4.setText("");
        et1.setText("");

        photoListN = new ArrayList<>();
        photoListY = new ArrayList<>();
        listType = new ArrayList<>();
        path = sspPhoto.getImgaddress();
        String plist = record10.getPlist();
        if (null != plist)
            if (plist.contains(",")) {
                for (String s : plist.split("\\,")) {
                    if (!TextUtils.isEmpty(s)) listType.add(s);
                }
            } else {
                if (TextUtils.isEmpty(plist)) listType.add("其他");
                else listType.add(plist);
            }
        bitmap0 = BitmapFactory.decodeFile(path);
        iv1.setBackground(new BitmapDrawable(bitmap0));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            issave = false;
            tv4.setText("");
            et1.setText("");
            tv6mark.setText("添加水印");
            switch (requestCode) {
                case 1://拍照
                    path = Environment.getExternalStorageDirectory() + "/" + Constant.TMP_PATH;
                    break;
                case 2://相册
                    path = CheckUtil.getFilePath(getActivity(), data.getData());
                    break;
                case 3:
                    hideWaitIngDialog();
                    break;
            }
            savePhoto(path);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        showListPhoto();
    }

    @SuppressLint("NewApi")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fp_mark_tv1://返回
                backtolastview();
                break;
            case R.id.fp_mark_tv3://拍照
                if (!issave) {
                    List<String> list = new ArrayList<>();
                    list.add("拍照提示");
                    list.add("当前数据还未保存!!\n请选择下一步操作后拍照");
                    list.add("舍弃");
                    list.add("保存");
                    MyDialog.recordDel(getActivity(), list, handler, "", 2, 3);
                } else {
                    openSheet(getActivity(), "选择方式", "相册", "拍照");
                }
                break;
            case R.id.fp_mark_tv5://保存
                updatelocalData(5);
                break;
            case R.id.fp_mark_layout1://照片类型
                PopwindowUtil.dropdownpop(getActivity(), listType, v, handler, 1);
                break;
            case R.id.fp_mark_tv6://设置水印
                String mark = String.valueOf(tv6mark.getText());
                if (mark.equals("添加水印")) {
                    tv6mark.setText("去除水印");
                    setWaterMarkWithPath(path);
                } else {
                    tv6mark.setText("添加水印");
                    iv1.setBackground(new BitmapDrawable(bitmap0));
                }
                break;
        }
    }

    //更新本地数据
    private void updatelocalData(final int i) {
        showWaitDialog(-1, "处理中...");
        issave = true;
        //照片保存处理
        String p = MyApp.File.getCachaPhotoPath_Record() + "/";

        if (fundtime == 0) fundtime = System.currentTimeMillis();
        if (path.contains(Constant.TMP_PATH)) {
            p += fundtime + "pz.jpg";
            sspPhoto.setImgname(fundtime + "pz.jpg");
        } else {
            p += fundtime + "xc.jpg";
            sspPhoto.setImgname(fundtime + "xc.jpg");
        }
        String mark = String.valueOf(tv6mark.getText());
        FileUtil.deleteFile(p);
        if (mark.contains("添加")) {
            CameraUtil.saveToString(path, p);
        } else {
            String temppath = Environment.getExternalStorageDirectory() + "/" + Constant.TMP_PATH;
            CameraUtil.saveBitmapFile(bitmap1, temppath);
            CameraUtil.saveToString(temppath, p);
        }
        sspPhoto.setImgaddress(p);
        //其他数据设置
        String ptype = String.valueOf(tv4.getText()).toString().trim();
        String remark = String.valueOf(et1.getText()).toString().trim();
        sspPhoto.setRemarks(remark);
        sspPhoto.setPlistone(ptype);
        List<SspPhoto> photos = new ArrayList<>();
        photos.addAll(photoListY);
        boolean isadd = true;
        for (SspPhoto photo : photos) {
            if (photo.getId().equals(sspPhoto.getId())) {
                isadd = false;
                break;
            }
        }
        if (isadd) {
            photoListY.add(0, sspPhoto);
        } else {
            for (SspPhoto photo : photoListY) {
                if (photo.getId().equals(sspPhoto.getId())) {
                    if (photo.getIsdel().equals("已同步")) photo.setIsdel("修改");
                    break;
                }
            }
        }
        photoListY.addAll(photoListN);
        saveToXml(FastJsonUtil.beanToJson(photoListY), record10.getGuid());
        UpdataRec();

        Message msg = handler.obtainMessage();
        msg.obj = "保存成功";
        msg.what = 4;
        msg.arg1 = i;
        handler.sendMessageDelayed(msg, 1500);
    }

    private void showListPhoto() {
        photoListY.clear();
        photoListN.clear();
        String photots = ShardPreferencesTool.getrecord(getActivity(), record10.getGuid(), "");
        List<SspPhoto> photoList = JSON.parseArray(photots, SspPhoto.class);
        if (photoList != null)
            for (SspPhoto photo : photoList) {
                if (!photo.getIsdel().equalsIgnoreCase("删除")) photoListY.add(photo);
                else photoListN.add(photo);
            }
    }

    private void backtolastview() {
        path = "";
        fundtime = 0;
        issave = false;
        tv4.setText("");
        et1.setText("");
        tv6mark.setText("添加水印");
        if (null != bitmap0) bitmap0.recycle();
        if (null != bitmap1) bitmap1.recycle();

        ((ProRecAndPicActivity) getActivity()).onBack(index, record10);
    }

    //设置照片数据
    @SuppressLint("NewApi")
    private void savePhoto(String path) {
        fundtime = System.currentTimeMillis();
        String millis = String.valueOf(fundtime);
        SspPhoto photo = new SspPhoto();
        photo.setId(millis);
        photo.setGuid(MString.getMyUUID());
        photo.setSid(MyApp.currProject.getStage_id());
        photo.setRguid(record10.getGuid());
        //保存时设置
//        photo.setPlistone(record10.getPlist());
//        photo.setRemarks("暂无，未设置");

        photo.setLongitude(String.valueOf(MyApp.bdLocation.getLongitude()));
        photo.setLatitude(String.valueOf(MyApp.bdLocation.getLatitude()));
        photo.setFounderid(MyApp.userInfo.getUser_id());
        photo.setFoundertime(millis);
        String name = path.substring(path.lastIndexOf("/") + 1);
        photo.setImgname(name);
        photo.setImgaddress(path);
        photo.setImgurl("");
        photo.setIsdel("新增");
        photo.setLasttime(millis);

        sspPhoto = null;
        bitmap0 = null;
        sspPhoto = photo;
        bitmap0 = BitmapFactory.decodeFile(path);
        iv1.setBackground(new BitmapDrawable(bitmap0));
    }

    //生成水印照片并显示
    @SuppressLint("NewApi")
    private void setWaterMarkWithPath(String path) {
        if (fundtime == 0) fundtime = System.currentTimeMillis();
        String str1 = record10.getPname();
        String str2 = TimeUtil.timeSFM(new Date(fundtime));
        String str3 = sspPhoto.getLongitude() + "\t" + sspPhoto.getLatitude();
//        Bitmap photo = BitmapFactory.decodeFile(path);
        Bitmap smallBitmap = CameraUtil.getSmallBitmap(path);
        Bitmap photo = CameraUtil.compressImage(smallBitmap);
        int width = photo.getWidth(), hight = photo.getHeight();
        bitmap1 = Bitmap.createBitmap(width, hight, Bitmap.Config.ARGB_8888); //建立一个空的BItMap
        Canvas canvas = new Canvas(bitmap1);//初始化画布绘制的图像到icon上

        Paint photoPaint = new Paint(); //建立画笔
        photoPaint.setDither(true); //获取跟清晰的图像采样
        photoPaint.setFilterBitmap(true);//过滤一些

        Rect src = new Rect(0, 0, photo.getWidth(), photo.getHeight());//创建一个指定的新矩形的坐标
        Rect dst = new Rect(0, 0, width, hight);//创建一个指定的新矩形的坐标
        canvas.drawBitmap(photo, src, dst, photoPaint);//将photo 缩放或则扩大到 dst使用的填充区photoPaint

        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);//设置画笔
        float y1 = hight - 200, y2 = y1 + 80, y3 = y2 + 80;
        if (hight > 1600) {
            textPaint.setTextSize(100.0f);//字体大小
            y1 = y1 - 40;
            y2 = y1 + 100;
            y3 = y2 + 100;
        } else {
            textPaint.setTextSize(40.0f);//字体大小
        }
        textPaint.setTypeface(Typeface.DEFAULT_BOLD);//采用默认的宽度
        textPaint.setColor(Color.RED);//采用的颜色
        //textPaint.setShadowLayer(3f, 1, 1,this.getResources().getColor(android.R.color.background_dark));//影音的设置
        canvas.drawText(str1, 20, y1, textPaint);//绘制上去字，开始未知x,y采用那只笔绘制
        canvas.drawText(str2, 20, y2, textPaint);//绘制上去字，开始未知x,y采用那只笔绘制
        canvas.drawText(str3, 20, y3, textPaint);//绘制上去字，开始未知x,y采用那只笔绘制
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        iv1.setBackground(new BitmapDrawable(bitmap1));
    }

    //修改记录数据状态
    private void UpdataRec() {
        List<SspRecord> recordList = new ArrayList<>();
        String jsonRec = ShardPreferencesTool.getrecord(getActivity(), MyApp.currProject.getStage_id(), "");
        if (!TextUtils.isEmpty(jsonRec)) {
            List<SspRecord> records = JSON.parseArray(jsonRec, SspRecord.class);
            if (records != null) {
                for (SspRecord record : records) {
                    if (!record.getIsdel().equalsIgnoreCase("删除")) {
                        if (record.getId().equals(record10.getId())) {
                            if (record10.getIsdel().equals("已同步")) {
                                record.setIsdel("修改");
                                record.setLasttime(String.valueOf(System.currentTimeMillis()));
                                recordList.add(0, record);//最新数据靠前存取
                            } else {
                                record.setLasttime(String.valueOf(System.currentTimeMillis()));
                                recordList.add(0, record);//最新数据靠前存取
                            }
                        } else {
                            recordList.add(record);
                        }
                    }
                }
            }
        }
        saveToXml(FastJsonUtil.beanToJson(recordList), MyApp.currProject.getStage_id());
    }

    //保存数据
    private void saveToXml(String json, String key) {
        ShardPreferencesTool.saverecord(getActivity(), key, json);
    }

    private void openSheet(Activity activity, final String... titles) {
        activity.setTheme(R.style.ActionSheetStyleIOS7);
        ActionSheet menuView = new ActionSheet(activity);
        menuView.setCancelButtonTitle("取消");// before add items
        menuView.addItems(titles);
        menuView.setItemClickListener(new ActionSheet.MenuItemClickListener() {
            @Override
            public void onItemClick(int itemPosition) {
                if (itemPosition == 0) return;
                if (itemPosition == 1) {
                    CameraUtil.pickPhoto(RegeditActivity.Code_Select);//相册
                } else {
                    CameraUtil.openCamera(RegeditActivity.Code_Pick);//拍照
                }
            }
        });
        menuView.setCancelableOnTouchMenuOutside(true);
        menuView.showMenu();
    }

    public void onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) backtolastview();
    }

    @Override
    public void onDestroyView() {
        if (null != bitmap0) bitmap0.recycle();
        if (null != bitmap1) bitmap1.recycle();
        super.onDestroyView();
    }
}
